<?php

declare(strict_types=1);

namespace App\Controller;

use App\Helps\Data;
use App\Middleware\AuthUser;
use App\Model\Menu;
use App\Model\User;
use App\Services\AuthService;
use App\Traits\UserTrait;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;


/**
 * @AutoController(prefix="api/auth")
 * Class AuthController
 * @package App\Controller
 */
class AuthController extends AbstractController
{
    use UserTrait;

    protected $authService;

    public function __construct( AuthService $authService)
    {
        $this->authService = $authService;
    }

    public function login(RequestInterface $request, ResponseInterface $response)
    {
        $inputs = $request->inputs(['username', 'password']);

        $user = User::query()->where(['username' => $inputs['username']])->first();

        if (!$user || $user->password != $inputs['password']) {
            return $response->json(['message' => '用户名或密码不存在', 'status' => STATUS_FAILURE]);
        }
        if ($user->token_expired_at < date('Y-m-d H:i:s')) {
            $token = md5($user->username . $user->password . time() . uniqid());
            $user->token = $token;
            $user->token_expired_at = date('Y-m-d H:i:s', strtotime('+1 week'));
            $user->save();
        }
        return $response->json(['message' => '登录成功', 'status' => STATUS_SUCCESS, 'token' => $user->token]);
    }

    /**
     * @Middlewares({@Middleware(AuthUser::class)})
     * @param RequestInterface $request
     * @param ResponseInterface $response
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function user(RequestInterface $request, ResponseInterface $response)
    {
        $authUser = $request->getAttribute('authUser');
        return $response->json(['data' => $authUser->toArray()+['avatar_url'=>$authUser->avatar[0]['url'] ?? ''], 'status' => STATUS_SUCCESS]);
    }

    /**
     * @Middlewares({@Middleware(AuthUser::class)})
     * @param ResponseInterface $response
     * @param RequestInterface $request
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function menus(ResponseInterface $response, RequestInterface $request)
    {
        $authUser = $request->getAttribute('authUser');
        $ownedMenus = !$authUser->is_super ?
            $this->authService->getNoSuperMenus($authUser) :
            Menu::query()->where([])->orderBy('sort')->get()->toArray();

        array_walk($ownedMenus, function (&$item) {
            $item['hideInMenu'] = !$item['visible'];
        });
        $treeList = Data::listToTree($ownedMenus, 'id', 'pid', 'children');
        return $response->json(['data' => $treeList, 'status' => STATUS_SUCCESS]);
    }
}
